<?php
/**
 *  date: 2017/7/10  11:03
 *  Author: Lin
 *  encoding:utf-8  language:PHP
 */
namespace Home\Controller;
use Home\Model\AnswerModel;

class AnswerController extends BaseController
{
    protected $_answerObject;

    public function _initialize()
    {
        parent::_initialize();
        $this->answerObject = new AnswerModel;
    }

    //首页
    public function answer_index()
    {
        $user_id = $this->user_id;
        $startTime = strtotime(date('Y-m-d 00:00:00',time()));
        $endTime = strtotime(date('Y-m-d 23:59:59'),time());
        //查找有没有提交过答题信息
        $res = M('answer_formalinfo')->where(array('user_id'=>$user_id))->select();
        if($res)
            $true_status = 1;
        else
            $true_status = -1;

        $map = array();
        $map['user_id'] = $user_id;
        $map['add_time'] = array('between',array($startTime,$endTime));
        $map['status'] = array('eq',1);

        //一天答题数
        $daycount = M('answer_formalinfo')->where($map)->count();
        //答题数量设置
        $explain = M('answer_num')->find();

        if($daycount >= $explain['every_day_num'])
            $chance = -1;
        else
            $chance = 1;

        //var_dump($chance);die;
        $this->assign('true_status',$true_status);
        $this->assign('chance',$chance);
        $this->assign('every_day_num',$explain['every_day_num']);
        $this->display('answer_index');
    }

    //打乱二维数组顺序
    public function shuffle_assoc($list) {
        if (!is_array($list)) return $list;
        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $list[$key];
        return $random;
    }
    //练习
    public function answer_test()
    {
        $answer = M('question_bank')->where('is_display=1')->select();

        $answer_count = count($answer);
        //随机取题
        $newQuestion = self::shuffle_assoc($answer);

        $explain = M('answer_num')->find();
        $this->assign('explain',$explain);
        $this->assign('answer_count',$answer_count);
        $this->assign('answer',$newQuestion);
        $this->display('answer_test');
    }

    //答题用户信息
    public function answer_true_form()
    {
        $this->display();
    }

    //信息提交
    public function adduser_answer_true()
    {
        $hModel = M('answer_formalinfo');
        $dataPost = I('post.');
        $dataPost['user_id'] = $this->user_id;
        $dataPost['is_first'] = 1;//标记第一次答题
        $id = $hModel->add($dataPost);
        if($id)
        {
            $this->ajaxReturn(array('status'=>1,'message'=>'信息提交成功！','url'=>'/Answer/answer_true#router2'));
        }
        $this->ajaxReturn(array('status'=>-1,'message'=>'信息提交失败，请重试！'));
    }


    //正式答题
    public function answer_true()
    {
        //答题数量设置
        $explain = M('answer_num')->find();
        $answer = M('question_bank')->where('is_display=1')->select();
        //随机题数
        $newId = array_rand($answer,$explain['formal_num']);
        $newQuestion = array();//随机题
        //$newkey = array();//随机题答案

        foreach ($newId as $k => $v)
        {
            $newQuestion[] = $answer[$v];
            //$newkey[] = strtolower($answer[$v]['exactness']);//全转小写
        }
        //session('key',$newkey);
        //排名
        self::report_user();
        //最后一次答题信息
        $last_answerinfo = M('answer_formalinfo')->where("user_id=$this->user_id AND status = 1")->order('id desc')->find();
        $last_answerinfo['true_num'] = intval($last_answerinfo['score']/$explain['score']);
        $last_answerinfo['false_num'] = $explain['formal_num'] - $last_answerinfo['true_num'];
        $last_answerinfo['accuracy'] =  round(($last_answerinfo['true_num']/$explain['formal_num'])*100,2);

        $this->assign('last',$last_answerinfo);
        $this->assign('explain',$explain);
        $this->assign('answer',$newQuestion);
        $this->display();
    }

    //更新开始答题时间和增加答题记录
    public function update_answer_time()
    {
        $user_id = $this->user_id;
        //最新一条
        $res = M('answer_formalinfo')-> where("user_id=$user_id")->order('id desc')->limit(1)->find();
        if($res)
        {
            //是第一条数据和答题状态没完成
            if($res['is_first'] == 1 && $res['status'] == 0)
            {
                $dataPost = array();
                $dataPost['start_time'] = time();
                //更新最后一条数据
                $result = M('answer_formalinfo')-> where("user_id=$user_id")->order('id desc')->limit(1)->save($dataPost);
                if($result !== false)
                    $this->ajaxReturn(array('status'=>1));
                else
                    $this->ajaxReturn(array('status'=>-1));
            }
            elseif ($res['is_first'] == 0 && $res['status'] == 0)
            {
                //上回答题没有完成的
                $dataPost = array();
                $dataPost['start_time'] = time();
                //更新最后一条数据
                $result = M('answer_formalinfo')-> where("user_id=$user_id")->order('id desc')->limit(1)->save($dataPost);
                if($result !== false)
                    $this->ajaxReturn(array('status'=>1));
                else
                    $this->ajaxReturn(array('status'=>-1));
            }
            else
            {
                //插入一条新的数据
                $dataPost = array();
                $dataPost['user_id'] = $user_id;
                $dataPost['province'] = $res['province'];
                $dataPost['city'] = $res['city'];
                $dataPost['area'] = $res['area'];
                $dataPost['school'] = $res['school'];
                $dataPost['start_time'] = time();
                $dataPost['is_first'] = 0;

                $id = M('answer_formalinfo')->add($dataPost);
                if($id)
                    $this->ajaxReturn(array('status'=>1));
                else
                    $this->ajaxReturn(array('status'=>-1));
            }
        }
    }

    //保存报告
    public function report()
    {
        $user_id = $this->user_id;
        $dataPost = array();
        $dataPost['score'] = I('score');//用户得分
        $dataPost['total_time'] = I('total_time');//答题用时
        $dataPost['add_time'] = time();
        $dataPost['end_time'] = time();
        $dataPost['status'] = 1;
        //$data['jifen'] = 0;
        //更新最后一条数据
        $res = M('answer_formalinfo')-> where("user_id=$user_id")->order('id desc')->limit(1)->save($dataPost);

        //增加抽奖机会
        //答题数量设置
        $gopricesocre = M('answer_num')->getField('gopricesocre');
        if($dataPost['score'] >= $gopricesocre)
            M('users')->where('id='.$user_id) ->setInc('luckdraw_num');


        if($res !== false)
            $this->ajaxReturn(array('status'=>1,'url'=>"/Answer/answer_true#router3"));
        else
            $this->ajaxReturn(array('status'=>-1));
    }


    //用户正式答题排信息
    public function report_user()
    {
        $user_id = $this->user_id;
        //用户基本信息
        $user_base_info = M('answer_formalinfo')->field('province,city,area,school')->where("is_first=1 AND user_id = $user_id")->find();

        //地区排名
        $map =array();
        $map['af.province'] = $user_base_info['province'];
        $map['af.city'] = $user_base_info['city'];
        $map['af.area'] = $user_base_info['area'];
        //SELECT user_id,MAX(score) as userscore,GROUP_CONCAT(score),MIN(total_time) as mix_time ,GROUP_CONCAT(total_time),GROUP_CONCAT(area) FROM `mt_answer_formalinfo` GROUP BY user_id,province,city,area ORDER BY userscore desc,mix_time ASC
        //SELECT user_id,MAX(score) as userscore,MIN(total_time) as mix_time  FROM `mt_answer_formalinfo` WHERE `province` = '广东省' AND `city` = '广州市' AND `area` = '天河区' GROUP BY user_id,province,city,area ORDER BY userscore desc,mix_time ASC
        //SELECT af.user_id,MAX(score) as userscore,MIN(total_time) as min_time,u.nickname FROM mt_answer_formalinfo af left join mt_users u ON u.id = af.user_id  WHERE af.province = '广东省' AND af.city = '广州市' AND af.area = '天河区' GROUP BY af.user_id,af.province,af.city,af.area ORDER BY userscore desc,min_time asc,af.id desc LIMIT 10
        $area_all_data = M('answer_formalinfo')
                        ->alias('af')
                        ->field('af.user_id,MAX(score) as userscore,MIN(total_time) as min_time,u.nickname,u.headimgurl')
                        ->join('left join mt_users u ON u.id = af.user_id')
                        ->order('userscore desc,min_time asc,af.id desc')
                        ->where($map)
                        ->group("af.user_id,af.province,af.city,af.area")
                        //->limit(10)
                        ->select();

        //取十条
        $area_data = array_slice($area_all_data,0,10);
        //个人排名
        $order = array();
        foreach ($area_all_data as $k => $v)
        {
            $order[] = $v['user_id'];
        }
        $user_area_order = array_search($user_id,$order) +1;//返回键名+1=排名

        //学校排名
        $shcoolmap =array();
        $shcoolmap['af.school'] = $user_base_info['school'];

        $shcool_all_data = M('answer_formalinfo')
            ->alias('af')
            ->field('af.user_id,MAX(score) as userscore,MIN(total_time) as min_time,af.school,u.nickname,u.headimgurl')
            ->join('left join mt_users u ON u.id = af.user_id')
            ->order('userscore desc,min_time asc,af.id desc')
            ->where($shcoolmap)
            ->group("af.user_id,af.school")
            ->limit(10)
            ->select();

        //取十条
        $school_data = array_slice($shcool_all_data,0,10);
        //个人排名
        $school_order = array();
        foreach ($shcool_all_data as $k => $v)
        {
            $school_order[] = $v['user_id'];
        }
        $user_school_order = array_search($user_id,$school_order) +1;//返回键名+1=排名

        //var_dump($user_school_order);die;




        //$this->assign('explain',$explain);
        $this->assign('baseinfo',$user_base_info);
        $this->assign('areadata',$area_data);
        $this->assign('schooldata',$school_data);
        $this->assign('user_area_order',$user_area_order);
        $this->assign('user_school_order',$user_school_order);
        //$this->display('answer_true');
    }





    /**
     *学习题文
     * @Date 201707
     * @Author Lin
     */
    public function learnEdit()
    {
        $lqModel = M('learn_question');
        if(IS_POST)
        {
            if($lqModel->create(I('post.'),2))
            {
                if(false !== $lqModel->save())
                {
                    $this->success('修改成功');
                    exit;
                }
            }
            $this->error($lqModel->getError());
        }
        $data = $lqModel->find();
        $this->assign('data',$data);
        $this->display();
    }

    /**
     *题库列表
     * @Date 201707
     * @Author Lin
     */
    public function questionList()
    {
        $data = $this->answerObject->getQuestionList(I('title'));

        //var_dump($data);die;
        $this->assign('data',$data[0]);
        $this->assign('page',$data[1]);
        $this->display();
    }

    /**
     *增加题目
     * @Date 201707
     * @Author Lin
     */
    public function addQuestion()
    {
        $model = M('question_bank');
        if (IS_POST)
        {
            if ($model->create(I('post.'), 1))
            {
                $data = I('post.');
                $data['exactness'] = strtolower($data['exactness']);
                if ($model->add($data))
                {
                    $this->success('添加成功', U('questionList'), 2);
                    exit;
                }
            }
            $this->error($model->getError());
        }
        $this -> display();
    }


    /**
     * 题库修改
     */
    public function questionEdit()
    {
        $id=I('id');
        $model = M('question_bank');
        if (IS_POST)
        {
            if ($data = $model->create(I('post.'),2))
            {
                $data = I('post.');
                $data['exactness'] = strtolower($data['exactness']);
                if (FALSE !== $model->save($data))
                {
                    $this->success('修改成功','questionList',1);
                    exit;
                }
            }
            $this->error($model->getError());
        }
        $data = $model ->where(array('id'=>$id)) ->find();
        $this -> assign('data', $data);
        $this -> display();
    }


    /**
     * 题库删除
     */
    public function questionDel()
    {
        if(!IS_AJAX) return;
        $result = M('question_bank')-> delete(intval($_GET['id']));
        if($result)
            $this -> ajaxReturn(array('status' => 1,'message' => '删除成功'));
        else
            $this -> ajaxReturn(array('status' => 2,'message' => '操作失败'));
    }

    /**
     *全选删除
     * @Date 201703
     * @Author Linsenquan
     */
    public function deleteAllQuestion()
    {
        if(!IS_POST)
            $this->error('非法操作');
        if(empty($_POST))
            $this->error('请选择要删除的信息！','',2);
        //var_dump($_POST);die;
        $result = $this->answerObject->deleteAllQuestion($_POST);

        if($result)
            $this->success('删除成功',U('questionList'),2);
        else
            $this->error('删除失败','',2);
    }

    /**
     *设置答题数
     * @Date 201707
     * @Author Lin
     */
    public function answerNum()
    {
        $numModel = M('answer_num');
        if(IS_POST)
        {
            //var_dump($_POST);die;
            if($numModel->create(I('post.'),2))
            {
                if(false !== $numModel->save())
                {
                    $this->success('修改成功');
                    exit;
                }
            }
            $this->error($numModel->getError());
        }
        $data = $numModel->find();
        $this->assign('data',$data);
        $this->display();
    }

    /**
     *答题列表
     * @Date 201707
     * @Author Lin
     */
    public function answerInfoList()
    {
        $username = I('username');
        $school = I('school');
        $area = I('area');
        $city = I('city');
        if($city)
        {
            $_city = explode('_',$city);
            $city =$_city[0];
            $areadata = M('Tree')->where (array('pid'=>$_city[1]) )->select();//处理第一次只选市搜索后再点区没有区/县数据返回的情况和搜索后选中状态
        }
       //var_dump($area);
        $data = $this->answerObject->getAnswerInfoList($username,$school,$area,$city);
        $province = M('Tree')->where (array('pid'=>6) )->select();//广东省

        $this->assign('province',$province);
        $this->assign('city',$_city[1]);
        $this->assign('area',$area);
        $this->assign('areadata',$areadata);

        $this->assign('data',$data[0]);
        $this->assign('page',$data[1]);
        $this->assign('p', I('get.p', 1));
        $this->assign('perCount', 10);
        $this->display();
    }

    /**
     * 答题删除
     */
    public function answerInfoDel()
    {
        if(!IS_AJAX) return;
        $result = $this->answerObject-> delete(intval($_GET['id']));
        if($result)
            $this -> ajaxReturn(array('status' => 1,'message' => '删除成功'));
        else
            $this -> ajaxReturn(array('status' => 2,'message' => '操作失败'));
    }

    /**
     * 信息修改
     */
    public function answerInfoEdit()
    {
        $id=I('id');
        $model = $this->answerObject;
        if (IS_POST)
        {
            if ($data = $model->create(I('post.'),2))
            {
                if (FALSE !== $model->save())
                {
                    $this->success('修改成功','answerInfoList',2);
                    exit;
                }
            }
            $this->error($model->getError());
        }
        $data = $model ->alias('info')->field('info.*,u.nickname')->where(array('info.id'=>$id))->join('LEFT JOIN __USERS__ u ON u.id=info.user_id')->find();
        $this -> assign('data', $data);
        $this -> display();
    }

    /**
     *全选删除
     * @Date 201703
     * @Author Linsenquan
     */
    public function deleteAllInfo()
    {
        //var_dump($_POST);die;
        if(!IS_POST)
            $this->error('非法操作');
        if(empty($_POST))
            $this->error('请选择要删除的信息！','',2);

        $result = $this->answerObject->deleteAllInfo($_POST);
        if($result)
            $this->success('删除成功',U('answerInfoList'),2);
        else
            $this->error('删除失败','',2);
    }


    public function getRegion(){
        $Region=M("tree");
        $map['pid']=$_REQUEST["pid"];
        $map['type']=$_REQUEST["type"];

        $list=$Region->where($map)->select();

        //var_dump($list);
        echo json_encode($list);
    }


    /**
     *状态展示
     * @Date 201707
     * @Author Lin
     */
    public function statusEdit()
    {
        $Id = I('Id');
        $status = I('status');
        //var_dump($menuId);var_dump($status);die;

        $result = M('question_bank')->where(array('id'=>$Id))->setField('is_display',$status);

        if ($result !== false)
            $this->ajaxReturn(array('status'=>1));
        else
            $this->ajaxReturn(array('status'=>0));
    }


}